# 百度通用翻译API,不包含词典、tts语音合成等资源，如有相关需求请联系translate_api@baidu.com
# coding=utf-8
import http.client
import hashlib
import urllib
import random
import json

appid =  # 填写你的appid
secretKey =   # 填写你的密钥
myurl = '/api/trans/vip/translate'

def getre(q, httpClient, fromLang="auto", toLang="zh"):
    if q == "" or q == "":
        return {'trans_result': [{'dst': q}]}
    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
    except:
        return {'trans_result': [{'dst': q}]}
    appid =  # 填写你的appid
    secretKey =  # 填写你的密钥
    myurl = '/api/trans/vip/translate'
    salt = random.randint(32768, 65536)
    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
        q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
        salt) + '&sign=' + sign
    result =""
    try:
        httpClient.request('GET', myurl)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
    except Exception as e:
        print(e)
        return {'trans_result': [{'dst': q}]}
    finally:
        if httpClient:
            httpClient.close()
        return result


def getpicre(img, ):
    import requests
    import base64
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general"
    # 二进制方式打开图片文件
    #f = open('[本地文件]', 'rb')

    params = {"image": img}
    access_token = get_acctoken()
    request_url = request_url + "?access_token=" + access_token+"?vertexes_location=true"
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        return response.json()
    return

def get_acctoken(clientid,clientsec):
    import requests
    host = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+clientid+"&client_secret="+clientsec
    response = requests.get(host)
    if response:
        return str(response.json()['access_token'])
